package cn.edu.nbpt.campus_api.service.blog.impl;

import cn.edu.nbpt.campus_api.exception.BizException;
import cn.edu.nbpt.campus_api.mapper.blog.CategoryMapper;
import cn.edu.nbpt.campus_api.model.ErrorCode;
import cn.edu.nbpt.campus_api.model.Page;
import cn.edu.nbpt.campus_api.model.blog.entity.Article;
import cn.edu.nbpt.campus_api.model.blog.entity.Category;
import cn.edu.nbpt.campus_api.service.blog.CategoryService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public Page<Category> selectCategoryList(String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.selectCategoryList(name);
        return Page.page(categories);
    }

    @Override
    public Category selectCategory(Integer id) {
        Category category = categoryMapper.selectCategory(id);
        if (category == null) throw new BizException(ErrorCode.SELECT_ERROR);
        return category;
    }

    @Override
    public Integer insertCategory(Category category) {
        category.setCreateBy("admin");
        category.setCreateTime(new Date());
        Integer row = categoryMapper.insertCategory(category);
        if (row == 0) throw new BizException(ErrorCode.INSERT_ERROR);
        return category.getId();
    }

    @Override
    public Integer updateCategory(Category category) {
        category.setUpdateBy("admin");
        category.setUpdateTime(new Date());
        Integer row = categoryMapper.updateCategory(category);
        if (row == 0) throw new BizException(ErrorCode.UPDATE_ERROR);
        return category.getId();
    }

    @Override
    public Integer deleteCategory(List<Integer> ids) {
        Integer row = categoryMapper.deleteCategory(ids);
        if (row == 0) throw new BizException(ErrorCode.DELETE_ERROR);
        return row;
    }
}
